package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Room;
import com.gaohe.service.RoomService;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("room")
public class RoomController {
    @Autowired
    RoomService roomService;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/page")
    private R page(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam(required = false) String name)
    {
        Page<Room>page1 = new Page<>();
        LambdaQueryWrapper<Room> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(!StringUtils.isEmpty(name),Room::getName,name);
        lambdaQueryWrapper.orderByDesc(Room::getUpdateTime);
        return R.success(roomService.page(page1,lambdaQueryWrapper));
    }
//    添加
    @PostMapping
    private R save(@RequestBody Room room, HttpSession session)
    {
        room.setStatus(1);
        Long user = (Long)redisTemplate.opsForValue().get("auth");
//        Long user = (Long) session.getAttribute("user");
        room.setCreateUser(user);
        room.setUpdateUser(user);
        room.setCreateTime(LocalDateTime.now());
        room.setUpdateTime(LocalDateTime.now());
        boolean flag = roomService.save(room);
        return flag?R.success("添加成功"):R.error("添加失败");
    }

//  修改状态
    @PutMapping("/changeStatus")
    private R changeStatus(@RequestBody Room room,HttpSession session)
    {
        Long user = (Long)redisTemplate.opsForValue().get("auth");
//        Long user = (Long) session.getAttribute("user");
        room.setUpdateUser(user);
        room.setUpdateTime(LocalDateTime.now());
        boolean flag = roomService.updateById(room);
        return flag?R.success("修改成功"):R.error("修改失败");
    }

    //    获取id
    @GetMapping("{id}")
    private R getId(@PathVariable Long id)
    {
        return R.success(roomService.getById(id));
    }

//    修改数据
    @PutMapping
    private R update(@RequestBody Room room)
    {
        room.setUpdateTime(LocalDateTime.now());
        boolean flag = roomService.updateById(room);
        return flag?R.success("修改成功"):R.error("修改失败");
    }

//    删除数据
    @DeleteMapping
    private R delete(Long id)
    {
//        这里设定的删除不合理
//        Room room = roomService.getById(id);
//        room.setIsDeleted(1);
//        room.setUpdateTime(LocalDateTime.now());
        boolean flag = roomService.removeById(id);
        return flag?R.success("删除成功"):R.error("删除失败");
    }

}
